import { ref, watch } from "vue"

export function useScrollNavigation(businessTypes: any, OFFSET: number) {
	const itemPositions = ref<any>([])
	const currentIndex = ref(0)
	const isClickScroll = ref(false)

	// 监听businessTypes的变化
	watch(businessTypes, async (newBusinessTypes) => {
		// 当businessTypes有新值时，重新获取元素位置信息
		await getElementPositions(newBusinessTypes)
	})

	const updateActiveIndex = (scrollTop: number) => {
		const adjustedScrollTop = scrollTop + OFFSET + 100
		let activeIndex = -1

		for (let i = 0; i < itemPositions.value.length; i++) {
			const item = itemPositions.value[i]
			if (adjustedScrollTop >= item.top && adjustedScrollTop < item.bottom) {
				activeIndex = item.index
				break
			}
		}

		if (activeIndex !== -1 && currentIndex.value !== activeIndex) {
			currentIndex.value = activeIndex
		}
	}

	const getElementPositions = (businessTypesToUse = businessTypes.value) => {
		return new Promise((resolve) => {
			const query = uni.createSelectorQuery()
			businessTypesToUse.forEach((_: any, index: number) => {
				query.select(`#ticket-${index}`).boundingClientRect()
			})
			query.exec((res) => {
				itemPositions.value = res
					.map((item: any, index: number) => ({
						index,
						top: item?.top,
						bottom: item?.bottom,
						height: item?.height,
					}))
					.filter(Boolean)
				resolve(true)
			})
		})
	}

	const handleCategoryClick = async (index: number) => {
		currentIndex.value = index
		isClickScroll.value = true

		const targetPosition = itemPositions.value[index].top - OFFSET
		uni.pageScrollTo({
			scrollTop: targetPosition,
			duration: 300,
			success: () => {
				setTimeout(() => {
					isClickScroll.value = false
				}, 300)
			},
		})
	}

	return {
		currentIndex,
		isClickScroll,
		updateActiveIndex,
		getElementPositions,
		handleCategoryClick,
	}
}
